package main

import (
	"bufio"
	"fmt"
	"os"
	"time"

	kingpin "gopkg.in/alecthomas/kingpin.v2"
)

var (
	ifile     = kingpin.Flag("ifile", "输入文件路径").Short('f').Default("./click1-%Y%m%d-%H%M.log").String()
	splitTime = kingpin.Flag("stime", "文件切割频率 def:1m  (1ns,1s,1m,1h)").Short('s').Default("1m").Duration()

	cleanbool = kingpin.Flag("cbool", "是否清理数据").Short('b').Default("false").Bool()
	cfile     = kingpin.Flag("cfile", "清理文件路径").Short('c').Default("./click1-*.log").String()
	cleanTime = kingpin.Flag("ctime", "清理间隔时间 def:48h  (1ns,1s,1m,1h)").Short('t').Default("24h").Duration()
)

func init() {
	kingpin.Version("0.0.1")
	kingpin.HelpFlag.Short('h')
	kingpin.Parse()
	//fmt.Printf("Would ping: %s with timeout %s and count %d\n", *ip, *timeout, *count)
}

func main() {

	fmt.Println("Write to " + *ifile)

	if *cleanbool {
		fmt.Println("open clean thread..." + *cfile)
		go clean(*cfile, *cleanTime, *splitTime)
	}

	w, err := NewTimeBasedRotator(*ifile, *splitTime)
	if err != nil {
		fmt.Printf("%v\n", err)
	}

	s := bufio.NewScanner(os.Stdin)
	for s.Scan() {
		w.Writeln(s.Bytes())
	}

}

func clean(s string, cleanTime, splitTime time.Duration) {

	//清除至少 7 天内未修改的所有旧日志文件
	cleaner, err := NewTimeBasedCleaner(s, cleanTime)
	if err != nil {
		fmt.Printf("%v\n", err)
	}
	ticker := time.NewTicker(splitTime)
	for {
		<-ticker.C
		cleaner.Clean()
	}

}
